from django.db import transaction
from rest_framework import serializers

from apps.goods.models import SKU, GoodsCategory, SPU, SPUSpecification, SpecificationOption, SKUSpecification


# 定义和 SKUSpecification 关联的序列化器
class SKUSpecificationSerializer(serializers.ModelSerializer):
    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()

    class Meta:
        model = SKUSpecification
        fields = ['spec_id', 'option_id']


class SKUSerializer(serializers.ModelSerializer):
    spu_id = serializers.IntegerField()
    category_id = serializers.IntegerField()

    category = serializers.StringRelatedField()
    spu = serializers.StringRelatedField()

    specs = SKUSpecificationSerializer(many=True)

    class Meta:
        model = SKU
        fields = '__all__'

    def create(self, validated_data):
        specs_data = validated_data.pop('specs')

        with transaction.atomic():
            # 开启事务点
            save_point = transaction.savepoint()
            # 通过对字典数据的解包来保存sku
            sku = SKU.objects.create(**validated_data)

            # 对内层数据数据进行遍历
            for spec_data in specs_data:
                # 设置外键关系
                SKUSpecification.objects.create(sku=sku, **spec_data)
            # 保存事务
            transaction.savepoint_commit(save_point)
        return sku

    # def create(self, validated_data):
    #     specs_data = validated_data.pop('specs')
    #     with transaction.atomic():
    #         save_point = transaction.savepoint()
    #         sku = SKU.objects.create(**validated_data)
    #         for spec_data in specs_data:
    #             SKUSpecification.objects.create(sku=sku, **spec_data)
    #         transaction.savepoint_commit(save_point)
    #     return sku


# 三级分类 序列化器
class GoodsCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = ['id', 'name']


# SPU的序列化器
class SimpleSPUSerializer(serializers.ModelSerializer):
    class Meta:
        model = SPU
        fields = ['id', 'name']


# 规格选项
class OptionModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = SpecificationOption
        fields = ['id', 'value']


# 商品SPU规格序列化器
class SPUSpecModelSerializer(serializers.ModelSerializer):
    # 根据模型中的,隐藏字段
    # 来获取 规格选项信息
    options = OptionModelSerializer(many=True)

    class Meta:
        model = SPUSpecification
        # fields = ['id', 'name']
        fields = ['id', 'name', 'options']
